package com.fengycx.templeate;

import com.fengycx.properties.WechatPayProp;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import com.wechat.pay.java.service.profitsharing.model.*;
import org.springframework.context.annotation.Configuration;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Map;

@Configuration
public class WechatJsapiPayTemplate {

    private WechatPayProp wechatPayProp;

    private Config config;

    private JsapiServiceExtension service;

    private ProfitsharingService profitsharingService;

    public WechatJsapiPayTemplate(WechatPayProp wechatPayProp, Config config, JsapiServiceExtension service,ProfitsharingService profitsharingService) {
        this.wechatPayProp=wechatPayProp;
        this.config=config;
        this.service=service;
        this.profitsharingService=profitsharingService;
    }

    /**
     *
     * @param openId
     * @param amount
     * @param outOrderNo  商户分账单号
     * @param transactionId 微信支付订单号
     */
    public OrdersEntity  profitSharingHandler(String openId, BigDecimal amount,String outOrderNo,String transactionId){
        //添加分账人
        AddReceiverRequest addReceiverRequest = new AddReceiverRequest();
        String appId = wechatPayProp.getAppId();
        addReceiverRequest.setAppid(appId);
        addReceiverRequest.setType(ReceiverType.PERSONAL_OPENID);
        addReceiverRequest.setAccount(openId);
        addReceiverRequest.setRelationType(ReceiverRelationType.STAFF);


        //请求分账
        CreateOrderRequest createOrderRequest = new CreateOrderRequest();
        createOrderRequest.setAppid(appId);
        createOrderRequest.setTransactionId(transactionId);
        createOrderRequest.setOutOrderNo(outOrderNo);
        ArrayList<CreateOrderReceiver> createOrderReceivers = new ArrayList<>();
        CreateOrderReceiver createOrderReceiver = new CreateOrderReceiver();
        createOrderReceiver.setType("PERSONAL_OPENID");
        createOrderReceiver.setAccount(openId);
        createOrderReceiver.setAmount(amount.longValue());
        createOrderReceiver.setDescription("利润分账");
        createOrderReceivers.add(createOrderReceiver);

        createOrderRequest.setReceivers(createOrderReceivers);
        createOrderRequest.setUnfreezeUnsplit(true); //是否解冻剩余未分资金,如果为true，该笔订单剩余未分账的金额会解冻回分账方商户；
        return profitsharingService.createOrder(createOrderRequest);



    }


    /**
     *
     * @param openId 支付账单用户openid
     * @param payOrderNo 生成的支付单号
     * @param totalMoneyUnitCent 总金额，单位：分
     * @param description 描述
     * @return
     */
    public PrepayWithRequestPaymentResponse prePay(String payOrderNo,Integer totalMoneyUnitCent,String openId,String description){
        PrepayRequest request = new PrepayRequest();
        // 调用request.setXxx(val)设置所需参数，具体参数可见Request定义
        // 调用接口
        Amount amount = new Amount();
        //单位为 元角分的分
        amount.setTotal(1);
        request.setAmount(amount);
        //小程序appid
        request.setAppid(wechatPayProp.getAppId());
        //商户号
        request.setMchid(wechatPayProp.getMerchantId());
        request.setDescription(description);
        //回调url
        request.setNotifyUrl(wechatPayProp.getNotifyUrl());
        //生成的支付单号
        request.setOutTradeNo(payOrderNo);
        Payer payer =new Payer();
        //支付人的openId
        payer.setOpenid(openId);
        request.setPayer(payer);

        // 调用下单方法，得到应答，前端使用小程序调起支付：
        PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
        // 使用微信扫描 code_url 对应的二维码，即可体验Native支付
        System.out.println(response);
        return response;
    }


    /**
     * 微信支付结果回调，验签、解密
     * 返回的对象 Transaction 根据你使用的微信支付类型来决定，此次使用的jsapi
     * @param body
     * @param headers
     * @return
     */
    public Transaction parse(String body , Map<String,String> headers){
        RequestParam requestParam = new RequestParam.Builder()
        .serialNumber(headers.get("wechatpay-serial"))
        .nonce(headers.get("wechatpay-noce"))
        .signature(headers.get("wechat-signature"))
        .timestamp(headers.get("wechat-timestamp"))
        .body(body)
        .build();

        //初始化 NotificationParser
        NotificationParser parser = new NotificationParser((NotificationConfig) config);

        //以支付 通知回调为例，验签，解密并替换成 Transaction
        return parser.parse(requestParam, Transaction.class);
    }
}
